<template>
  <!-- :action="upload.url" -->
  <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
      <el-upload
        ref="upload"
        :limit="limit"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-preview="handleUploadPreview"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="fileChange"
        :on-remove="fileRemove"
        :on-error="uploadFalse"
        :http-request="uploadFile"
        :auto-upload="false"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>请按照模版上传文件，一次仅支持导入一个文件,仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <!-- <span v-if="this.fileMessage.length != 0" style="margin-top:10px">{{this.fileMessage}}</span> -->
      <div style="margin-top:10px; max-height: 200px; background-color: pink; overflow: auto;">
        <el-table :data="fileMessage" v-if="this.fileMessage.length != 0"  style="" :row-style="{height:'47px'}">
          <el-table-column label="序号" align="left" type="index" width="60"/>
          <el-table-column label="失败原因" align="left" prop="notPassed"></el-table-column>
        </el-table>
      </div>
      
      <span v-if="fileMessageData.totalNum && this.fileMessage.length != 0" style="margin-top:10px">
        数据验证结果：共验证导入数据 <span style="color:#1890FF">{{fileMessageData.totalNum}}</span> 条，
        验证通过 <span style="color:#52C41A">{{fileMessageData.successNum}}</span> 条，
        验证失败 <span style="color:#FF4D4F">{{fileMessageData.failNum}}</span> 条</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import {uploadPostFile} from '@/api/basic/uploadFile.js'

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    uploadUrl: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 1,
    },
    // fileData: {
    //   type: Array,
    //   default: [],
    // },
    isUploadShow: {
      type: Boolean,
      default: false,
    },
    downloadTemplateUrl: { // 下载模板url
      type: String,
      default: ''
    },
    downloadTemplateName: { // 下载模板文件名
      type: String,
      default: '模板文件'
    }
  },
  watch: {
    // fileData: {
    //   handler(newVal) {
    //     this.fileList = newVal;
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    title: {
      handler(newVal) {
        this.upload.title = newVal;
      },
      deep: true,
      immediate: true,
    },
    uploadUrl: {
      handler(newVal) {
        this.upload.url = process.env.VUE_APP_BASE_API + newVal;
      },
      deep: true,
      immediate: true,
    },
    // isUploadShow: { // 是否显示弹窗
    //   handler(newVal) {
    //     this.upload.open = newVal;
    //   },
    //   deep: true,
    //   immediate: true,
    // }
  },
  data() {
    return {
      fileList: [], // 上传使用
      // 商品导入参数
      upload: {
        // 是否显示弹出层（商品导入）
        open: false,
        // 弹出层标题（商品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: '', //process.env.VUE_APP_BASE_API + "/basic/data/tenant/goods/goodsImport"
      },
      fileMessage:[], // 上传错误信息
      fileMessageData:{}, // 上传返回
    }
  },
  methods: {

    /**
     * 显示弹窗
     */
    show() {
      this.fileMessageData = {};
      this.fileMessage = [];
      this.fileList = [];
      this.upload.open = true;
    },

    cancel() {
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    
    /**
     * 下载客户商品导入模板
     */
     importTemplate() {
      this.downloadFile(this.downloadTemplateUrl, {}, `${this.downloadTemplateName}.xls`)
      // this.downloadFile('/basic/data/tenant/goods/excelTemplateDownload', {}, `客户商品导入模板.xlsx`);
    },

    /**
     * 商品导入改变时的钩子
     * @param {*} file 
     * @param {*} fileList 
     */
    fileChange(file, fileList) {
      // console.log('fileChange');
      this.file = file.raw;
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; // 获取最后一次选择的文件
      }

      this.fileMessageData = {};
      this.fileMessage = [];
    },

    /**
     * 删除文件
     * @param {*} file 
     * @param {*} fileList 
     */
    fileRemove(file, fileList) {
      // console.log('fileList=', fileList);
      this.fileList = fileList;
    },

    /**
     * 商品导入中处理
     * @param {*} event 
     * @param {*} file 
     * @param {*} fileList 
     */
    handleFileUploadProgress(event, file, fileList) {
      // console.log('handleFileUploadProgress');
      this.upload.isUploading = true;
    },

    /**
     * 商品导入成功处理
     * @param {*} response 
     * @param {*} file 
     * @param {*} fileList 
     */
    handleFileSuccess(response, file, fileList) {
      // console.log('handleFileSuccess=', response);
      if (response == undefined) {
        return;
      }
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.fileMessage = [];
      // console.log('response=', response);
      if (response.code == 200) {
        this.fileMessageData = response.data?response.data:{};
        if(response.data && response.data.errorList && response.data.errorList.length > 0){
          this.$modal.msgError('导入失败')
          const errorList = response.data.errorList;
          errorList && errorList.forEach(item => {
            this.fileMessage.push({notPassed:item})
          });
        } else if (response.data && (response.data.errorList == null || response.data.errorList == undefined || response.data.errorList.length == 0)) {
          this.$modal.msgSuccess('导入成功');
          this.upload.open = false;
          // this.onRefreshTable();
          this.$emit('refreshData',response.data.tenantGoods);

        }else if(response.data ==null){
          this.$modal.msgSuccess('导入成功');
          this.upload.open = false;
          // this.onRefreshTable();
          this.$emit('refreshData',response.data.tenantGoods);
        }
      } else {
        // console.log('哈哈哈=');
        if (response.hasOwnProperty('code')) {
          this.$modal.msgError(response.msg)
        }
      }
    },

    async handleUploadPreview(file) {
      // console.log('preUpload=', file);
    },

    /**
     * 上传
     * @param {*} params 
     */
    async uploadFile(params) {
      // console.log('uploadFile.params====', params);
      this.upload.isUploading = true;
      const file = params.file;
      let form = new FormData();
      form.append("file", file);
      // console.log('uploadUrl=', this.uploadUrl);
      uploadPostFile(this.uploadUrl, form).then(res => {
        // console.log('上传res=', res);
        this.handleFileSuccess(res);
      }).catch(err => {
        // console.log('山川=', err);
        this.handleFileSuccess(err);
      });
    },

    /**
     * 文件上传失败绑定的钩子函数
     * @param {*} response 
     * @param {*} file 
     * @param {*} fileList 
     */
    uploadFalse(response, file, fileList) {
      /*
      console.log('currentTarget=', response);
      // 处理超时情况 response包含currentTarget.timeout属性，其值为0。
      if ((response.currentTarget.timeout + '').indexOf('0') > -1) {
        this.$message({
          showClose: true,
          message: '正在处理...!',
          type: 'info',
          offset: 200,
          duration: 0
        });
      } else {
        this.$message({
          showClose: true,
          message: '文件上传失败!',
          type: 'error',
          offset: 200,
          duration: 0
        });
      }*/
    },

    /**
     * 提交导入商品
     */
     submitFileForm() {
      console.log('fileLIst=', this.fileList);
      if (this.fileList.length == 0) {
        this.$modal.msgWarning("请上传文件");
        return;
      }
      
      this.$refs.upload.submit();
    },

  },
}
</script>

<style scoped lang="scss">
.upload-file-con {

}
::v-deep .el-upload-dragger{
  // margin-left: 18%!important;
  width: 558px;
}
</style>